import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

/// 日志修改器
/// 负责记录请求和响应日志
class LoggerModifier {
  /// 请求修改器
  Future<Request> requestModifier(Request request) async {
    if (kDebugMode) {
      try {
        print('┌─────────────────────────────────────────────────────────────────────────────');
        print('│ 🚀 REQUEST: [${request.method}] ${request.url}');
        print('├─────────────────────────────────────────────────────────────────────────────');
        
        // 打印请求头
        if (request.headers.isNotEmpty) {
          print('│ 📝 Headers:');
          request.headers.forEach((key, value) {
            // 隐藏敏感信息
            if (key.toLowerCase() == 'authorization') {
              print('│   $key: Bearer ****');
            } else {
              print('│   $key: $value');
            }
          });
        }
        
        // 打印查询参数
        if (request.url.queryParameters.isNotEmpty) {
          print('│ 🔍 Query Parameters:');
          request.url.queryParameters.forEach((key, value) {
            print('│   $key: $value');
          });
        }
        
        // 打印请求体
        if (request.bodyBytes.isNotEmpty) {
          print('│ 📦 Body:');
          if (request.contentType?.contains('application/json') == true) {
            try {
              final jsonData = json.decode(utf8.decode(request.bodyBytes));
              final prettyJson = const JsonEncoder.withIndent('  ').convert(jsonData);
              prettyJson.split('\n').forEach((line) {
                print('│   $line');
              });
            } catch (e) {
              print('│   (无法解析JSON) ${utf8.decode(request.bodyBytes)}');
            }
          } else if (request.contentType?.contains('multipart/form-data') == true) {
            print('│   (Multipart Form Data, 大小: ${request.bodyBytes.length} bytes)');
          } else {
            print('│   ${utf8.decode(request.bodyBytes)}');
          }
        }
        
        print('└─────────────────────────────────────────────────────────────────────────────');
      } catch (e) {
        print('记录请求信息时出错: $e');
      }
    }
    
    return request;
  }
  
  /// 响应修改器
  Future<Response> responseModifier(Request request, Response response) async {
    if (kDebugMode) {
      try {
        print('┌─────────────────────────────────────────────────────────────────────────────');
        print('│ 📨 RESPONSE: [${request.method}] ${request.url}');
        print('│ 📊 Status Code: ${response.statusCode}, Status Text: ${response.statusText}');
        print('├─────────────────────────────────────────────────────────────────────────────');
        
        // 打印响应头
        if (response.headers != null && response.headers!.isNotEmpty) {
          print('│ 📝 Headers:');
          response.headers!.forEach((key, value) {
            print('│   $key: $value');
          });
        }
        
        // 打印响应体
        if (response.bodyBytes.isNotEmpty) {
          print('│ 📦 Body:');
          if (response.headers?['content-type']?.contains('application/json') == true) {
            try {
              final jsonData = json.decode(utf8.decode(response.bodyBytes));
              final prettyJson = const JsonEncoder.withIndent('  ').convert(jsonData);
              prettyJson.split('\n').forEach((line) {
                print('│   $line');
              });
            } catch (e) {
              print('│   (无法解析JSON) ${utf8.decode(response.bodyBytes)}');
            }
          } else if (response.headers?['content-type']?.contains('image/') == true) {
            print('│   (图片数据, 大小: ${response.bodyBytes.length} bytes)');
          } else {
            // 尝试以文本形式打印
            try {
              final text = utf8.decode(response.bodyBytes);
              if (text.length > 1000) {
                print('│   ${text.substring(0, 1000)}... (截断, 总长度: ${text.length})');
              } else {
                print('│   $text');
              }
            } catch (e) {
              print('│   (二进制数据, 大小: ${response.bodyBytes.length} bytes)');
            }
          }
        }
        
        // 打印请求耗时
        if (response.request != null) {
          final diff = response.headers?['date'] != null 
              ? DateTime.now().difference(response.request!.createdTime)
              : null;
          if (diff != null) {
            print('│ ⏱️ 请求耗时: ${diff.inMilliseconds}ms');
          }
        }
        
        print('└─────────────────────────────────────────────────────────────────────────────');
      } catch (e) {
        print('记录响应信息时出错: $e');
      }
    }
    
    return response;
  }
  
  /// 截断过长的响应体
  String _truncateBody(String body) {
    const maxLength = 500;
    if (body.length > maxLength) {
      return '${body.substring(0, maxLength)}... (已截断，总长度: ${body.length})';
    }
    return body;
  }
} 